//
//  IndentsViewController.m
//  Medgretraining
//
//  Created by 辰领科技 on 16/5/17.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "IndentsViewController.h"
#import "IndentsTableViewCell.h"
#import "OrderdetailViewController.h"
#import "EvaluationViewController.h"
#import "PayTypeViewController.h"

static NSString * CellIndentfier = @"IndentsTableViewCell";


@interface IndentsViewController ()<
UITableViewDataSource,UITableViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong,nonatomic) NSMutableArray * indentsArray;
@end

@implementation IndentsViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([Common getLoginStatus]) {
//        [_indentsArray removeLastObject];
       [self.tableView.header beginRefreshing];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO =  1;
    _indentsArray = [NSMutableArray array];
    [self initViewLayout];
   
     [self addRefreshing];
    
    
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{

    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    

     _tableView.frame = CGRectMake(0, 64* VerticalRatio(), 320* VerticalRatio(), 504* VerticalRatio()-49);
    
    [self.tableView registerNib:[UINib nibWithNibName:CellIndentfier bundle:nil] forCellReuseIdentifier:CellIndentfier];

}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
  
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (![Common getLoginStatus]) {
            [[AppDelegate sharedAppDelegate]ShowLoginPage];
            [_indentsArray removeAllObjects];
            [_tableView reloadData];
            [self.tableView.header endRefreshing];
            return ;
        }else{
            int64_t delayInSeconds = 8.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self.tableView.header endRefreshing];
            });
            self.pageNO = 1;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //请求订单数据
                [self getIndentsList];
            });
        }
    
    }];

}
//加载更多数据
- (void)loadMoreData{
    if (self.indentsArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getIndentsList];
        });
    }
}


#pragma mark === 订单列表
- (void)getIndentsList{
   
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:@"" forKey:@"mordStatus"];
    [dic setObject:[NSNumber numberWithInt:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInt:PageSize] forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:HK_queryAppMallOrder withHttpType:@"POST" withTag:HK_HK_queryAppMallOrder];
}

#pragma mark  == section上button点击事件
- (void)sectionButtonHandel:(UIButton *)sender{
    if ([sender.titleLabel.text isEqualToString:@"评 论"]) {

        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"IndentsStoryboard" bundle:nil];
        EvaluationViewController *evaluationVC = [secondStroyBoard instantiateViewControllerWithIdentifier:@"Evaluation"];
        
        evaluationVC.mgcoOrderDetailId = [NSString stringWithFormat:@"%@",_indentsArray[sender.tag - 200][@"mordId"]];
        evaluationVC.CommodityInformationDic = _indentsArray[sender.tag - 200];
        
        [[Common getNavigation]pushViewController:evaluationVC];
    }else if ([sender.titleLabel.text isEqualToString:@"支 付"]){
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"IndentsStoryboard" bundle:nil];
        PayTypeViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"PayType"];
        NSDictionary * dic = _indentsArray[sender.tag-200][@"goodsList"][0];
        page.payOrderPrice = [NSString stringWithFormat:@"%@",dic[@"mgooPrice"]];
        page.payOrderName = [NSString stringWithFormat:@"%@",dic[@"mgooName"]];
        page.payId = _indentsArray[sender.tag-200][@"mordNo"];
//        page.paySuccessBlock = ^(){
//            
//        };
        [[Common getNavigation]pushViewController:page];
    }
}

#pragma mark -- UITableViewDataSource


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35*VerticalRatio();
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 53*VerticalRatio();
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _indentsArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 93*VerticalRatio();
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 35), NO)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel * indentNumber = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(10, 0, 185, 35), NO)];
    indentNumber.textColor = [UIColor colorWithWhite:0.447 alpha:1.000];
    indentNumber.font = [UIFont systemFontOfSize:14*VerticalTexeRatio()];
    indentNumber.text = [NSString stringWithFormat:@"订单号:%@",_indentsArray[section][@"mordNo"]];
    [view addSubview:indentNumber];
    
    UILabel * indentTime = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(205 , 0, 110, 35), NO)];
    indentTime.textColor = [UIColor colorWithWhite:0.659 alpha:1.000];
    indentTime.font = [UIFont systemFontOfSize:13*VerticalTexeRatio()];
    NSString * time = [NSString stringWithFormat:@"%@",_indentsArray[section][@"createTime"]];
    if (time&&time.length>=16) {
        indentTime.text = [time substringToIndex:16];
    }
    
    [view addSubview:indentTime];
    
    UILabel * line = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(0, 34, 320, 1), NO)];
    line.backgroundColor = [UIColor colorWithWhite:0.953 alpha:1.000];
    [view addSubview:line];
    
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 53), NO)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel * indentprice = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(15, 0, 180,47), NO)];
    indentprice.textColor = [UIColor colorWithWhite:0.447 alpha:1.000];
    indentprice.font = [UIFont systemFontOfSize:15*VerticalTexeRatio()];
    CGFloat price = [[NSString stringWithFormat:@"%@",_indentsArray[section][@"mgooPrice"]]floatValue];
    NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"总金额:￥%.2f",price]];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.839 green:0.220 blue:0.220 alpha:1.000] range:NSMakeRange(4, str.length-4)];
    indentprice.attributedText = str;
    [view addSubview:indentprice];
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = flexibleFrame(CGRectMake(200, 7, 108, 32), NO);
    button.layer.cornerRadius = 15*VerticalRatio();
    button.backgroundColor = [UIColor colorWithRed:0.992 green:0.412 blue:0.333 alpha:1.000];
    button.tag = 200+section;
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16*VerticalTexeRatio()];
    NSString  * status = [NSString stringWithFormat:@"%@",_indentsArray[section][@"mordStatus"]];
    if ([status isEqualToString:@"1"]) {
        status = @"支 付";
    }else if([status isEqualToString:@"2"]){
    status = @"支 付";
    }else if([status isEqualToString:@"3"]){
        status = @"评 论";
        button.backgroundColor = [UIColor colorWithRed:0.996 green:0.467 blue:0.004 alpha:1.000];
    }else if([status isEqualToString:@"4"]){
        status = @"交易成功";
        button.backgroundColor = [UIColor clearColor];
        [button setTitleColor:[UIColor colorWithRed:0.996 green:0.467 blue:0.004 alpha:1.000] forState:UIControlStateNormal];
    }
    [button setTitle:status forState:UIControlStateNormal];
    [button addTarget:self action:@selector(sectionButtonHandel:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    
    UILabel * line = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(0, 47, 320, 6), NO)];
    line.backgroundColor = [UIColor colorWithWhite:0.953 alpha:1.000];
    [view addSubview:line];
    

    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    IndentsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentfier];
    if (cell == nil) {
        cell= [[IndentsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIndentfier];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    NSDictionary * dic = _indentsArray[indexPath.section][@"goodsList"][0];
    NSString * image = [NSString stringWithFormat:@"%@",dic[@"mgooImage"]];
    if (image.length>0) {
        [cell.indentImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
    }
    cell.indentGoodsName.text =[NSString stringWithFormat:@"%@", dic[@"mgooName"]];
      cell.indentSize.text = [NSString stringWithFormat:@"面积:%@m²",dic[@"modeNum"]];
    
    NSString * price = [NSString stringWithFormat:@"%@",dic[@"mgooPrice"]];
    NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"价格:￥%@/m²",price]];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1.000 green:0.467 blue:0.004 alpha:1.000] range:NSMakeRange(str.length-price.length-4, price.length+4)];
    cell.indentPrice.attributedText = str;
    
  
    NSString * total = [NSString stringWithFormat:@"%.2f",[dic[@"mgooPrice"]floatValue]*[dic[@"modeNum"]floatValue]];
    NSMutableAttributedString * atotal = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"小计:￥%@/m²",total]];
    [atotal addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1.000 green:0.467 blue:0.004 alpha:1.000] range:NSMakeRange(atotal.length-total.length-4, total.length+4)];
    cell.indentTotalMoney.attributedText = atotal;

    
    return cell;
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"IndentsStoryboard" bundle:nil];
    OrderdetailViewController * page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"Orderdetail"];
    page.mordId = self.indentsArray[indexPath.row][@"mordId"];
    page.commentInfoDic = _indentsArray[indexPath.section];
    [[Common getNavigation]pushViewController:page];
    
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag==HK_HK_queryAppMallOrder) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.indentsArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.indentsArray addObject:entity];
                }
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
                
            });

            
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    [self dismissWaitDialog];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
